package com.dongdongshop.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.dongdongshop.constant.OssConstant;
import com.dongdongshop.data.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private OSS ossClient;

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        try {

            String name = file.getOriginalFilename();
            String suffix = name.substring(name.lastIndexOf("."));
            UUID uuid= UUID.randomUUID();
            //路径名字
            String objectName = OssConstant.OBJECTNAME+uuid+suffix;

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(OssConstant.BUCKETNAME, objectName,file.getInputStream());

            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            return Result.success(OssConstant.FILE_URL_PREFIX+"/"+objectName);
        } catch (OSSException oe) {
            System.out.println("捕获到 OSSException，这意味着您的请求已发送到 OSS“ +”，但由于某种原因被拒绝并显示错误响应");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
            return Result.error(oe.getMessage());
        } catch (IOException e) {
            return Result.error(e.getMessage());
        }
    }
}
